package com.bigdata.movieticketapi.common.utils;


import cn.hutool.json.JSONUtil;
import com.bigdata.movieticketapi.common.pojo.JsCode2Session;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class JsCode2SessionUtil {

    private static final String APPID = "wx3f5d9b628f06ab3b";
    private static final String APPSECRET = "1d4159408abfd70f88cd5a95f5a52547";


    public static JsCode2Session getJsCode2Session(String code) throws Exception {
        String accessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + APPID
                + "&secret=" + APPSECRET + "&js_code=" + code;

        URL url = new URL(accessTokenUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // 获取返回的字符
        InputStream inputStream = connection.getInputStream();
        int size = inputStream.available();
        byte[] bs = new byte[size];
        inputStream.read(bs);
        String message = new String(bs, "UTF-8");

        // 获取access_token
        return JSONUtil.toBean(message, JsCode2Session.class);
    }
}
